package com.ivy.parser.bus;

import cn.hutool.core.util.StrUtil;
import com.ivy.builder.graph.IvyCmp;
import com.yomahub.liteflow.builder.el.ELBus;
import com.yomahub.liteflow.builder.el.ELWrapper;
import com.yomahub.liteflow.builder.el.SwitchELWrapper;
import com.yomahub.liteflow.builder.el.ThenELWrapper;

import java.util.List;

public class ELBusSwitch {

    private ELWrapper wrapper;

    public static ELBusSwitch NEW(){
        return new ELBusSwitch();
    }

    public ELBusSwitch node(IvyCmp info){

        SwitchELWrapper switchELWrapper = ELBus.switchOpt(ELBusNode.node(info));
        if(StrUtil.isNotBlank(info.getCmpId())){
            switchELWrapper.id(info.getCmpId());
        }
        if(StrUtil.isNotBlank(info.getCmpTag())){
            switchELWrapper.tag(info.getCmpTag());
        }
        if(info.getCmpToEL() == null){
            String cmpTo = info.getCmpTo();
            String[] split = null;
            if(StrUtil.isNotBlank(cmpTo)){
                split = cmpTo.split(",");
            }
            if(split != null){
                switchELWrapper.to(split);
            }
        }else{
            List<ThenELWrapper> thenELWrapperList = (List<ThenELWrapper>) info.getCmpToEL();
            for (ThenELWrapper thenELWrapper : thenELWrapperList){
                switchELWrapper.to(thenELWrapper);
            }
        }
        if(info.getCmpDefaultOptEL() != null){
            switchELWrapper.defaultOpt(info.getCmpDefaultOptEL());
        }else if(StrUtil.isNotBlank(info.getCmpDefaultOpt())){
            switchELWrapper.defaultOpt(info.getCmpDefaultOpt());
        }

        if(StrUtil.isNotBlank(info.getCmpPre()) || StrUtil.isNotBlank(info.getCmpFinallyOpt())){
            ThenELWrapper then = ELBus.then(switchELWrapper);
            if(StrUtil.isNotBlank(info.getCmpPre())){
                then.pre(info.getCmpPre());
            }
            if(StrUtil.isNotBlank(info.getCmpFinallyOpt())){
                then.finallyOpt(info.getCmpFinallyOpt());
            }
            if(info.getCmpMaxWaitSeconds() != null){
                then.maxWaitSeconds(info.getCmpMaxWaitSeconds());
            }
            wrapper = then;
        }else{
            if(info.getCmpMaxWaitSeconds() != null){
                switchELWrapper.maxWaitSeconds(info.getCmpMaxWaitSeconds());
            }
            wrapper = switchELWrapper;
        }
        return this;
    }

    public String toEL(){
        return wrapper.toEL();
    }

    public String toEL(boolean format){
        return wrapper.toEL(format);
    }

    public ELWrapper toELWrapper(){
        return wrapper;
    }

}
